package com.xpec.canaan.util;

import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;

/**
 * Produce MD5 from a file
 * @author wilson shih
 *
 */
public class ProduceMD5 extends Thread {
	
	private File m_file;
	private TableElementRecorder m_recorder;
	private static final char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',  'e', 'f'}; 
	private ProcessSingleDirectoryRecorder m_dirRecorder;
	
	public ProduceMD5(File file, TableElementRecorder recorder, ProcessSingleDirectoryRecorder dirRecorder)
	{
		m_file = file;
		m_recorder = recorder;
		m_dirRecorder = dirRecorder;
	}
	
	public void run()
	{
		produceMD5FromFile(m_file);
	}
	
	public void produceMD5FromFile(File inputFile)
	{
		try{
			FileInputStream fin = new FileInputStream(inputFile);
			
			int fileSize = fin.available();
			byte[] reads = new byte[fileSize];
			fin.read(reads, 0, fileSize);
			
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(reads);
			
			byte[] digest = md.digest();
			
			
			char str[] = new char[16 * 2];   

			int k = 0;                               
			for (int i = 0; i < 16; i++) {          
				byte byte0 = digest[i];                
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];  
				                        
				str[k++] = hexDigits[byte0 & 0xf];            
			}
			String s = new String(str);
			m_recorder.addElements(inputFile.getName(), s);
			
			System.out.println(inputFile + "  :\t " + s);
			fin.close();
			
			m_dirRecorder.notifyFileFinished();			
		}
		catch(Exception ex)
		{
			System.err.println(ex);
		}
	}
	
}
